<template>
  <div id="sampleDelivery">
    <el-card class="box-card" style="margin:15px">
      <div style="margin-bottom:10px">
        <el-button size="small" type="primary" icon="el-icon-upload2" @click="clickDS">递送</el-button>
        <el-button size="small" @click="getList(basicData.model)">刷新</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%;padding:5px;"
        :header-cell-style="{
          background: '#333333',
          color: '#ffffff',
          textAlign: 'center'
        }"
        @selection-change="onSelectChange"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" prop="deliveryHospital" label="医院名称" />
        <el-table-column align="center" prop="deliveryDepart" label="部门名称" />
        <el-table-column align="center" prop="amount" label="样本总量" />
      </el-table>
      <el-pagination
        :current-page="basicData.current"
        :page-size="basicData.size"
        :total="total"
        layout="slot,total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <span
          v-if="tableData.length > 0"
          style="font-weight: 400;color:#606266"
        >已选中{{ tableData.length }}条，</span>
      </el-pagination>
    </el-card>

    <!-- 递送详情 -->
    <el-dialog :visible.sync="DSShow" width="80%" center custom-class="print-dialog">
      <span
        slot="title"
        class="dialog-title"
        style="font-size: 18px;font-weight: 400;color: #FFFFFF;"
      >递送详情</span>
      <div class="edit-dialog">
        <el-form
          ref="basicForm"
          :inline="true"
          :model="deleteFormData"
          :rules="deleteRules"
          class="demo-form-inline"
          size="small"
          label-width="120px"
        >
          <el-row>
            <div id="top-form">
              <el-col :span="8">
                <el-form-item label="条形码号：">
                  <el-input
                    size="mini"
                    style="width:100%"
                    v-model="deleteFormData.barCode"
                    @keyup.enter.native="queryBarCode"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行号：">
                  <div style="display:flex;align-items:center">
                    <el-input
                      style="width:50%"
                      size="mini"
                      placeholder="起始"
                      v-model="deleteFormData.startCode"
                    />
                    <span style="margin:0 10px">至</span>
                    <el-input
                      style="width:50%"
                      size="mini"
                      placeholder="终止"
                      v-model="deleteFormData.endCode"
                    />
                    <el-button
                      style="margin-left:25px !important"
                      size="mini"
                      type="primary"
                      @click="clickIndexSelect"
                    >选中</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </div>
            <!-- <el-col :span="24">
              <div style="height:1px;width:100%;margin:10px 0;background:#e8e8e8"></div>
            </el-col>
            <el-col :span="24">
              <el-col :span="12" style="padding-left:15%">
                <el-form-item label="母亲姓名：">
                  <span style="color:red">
                    {{
                    queryItem.momName ? queryItem.momName : ""
                    }}
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="padding-left:5%">
                <el-form-item label="条形码号：">
                  <span style="color:red">
                    {{
                    queryItem.barCode ? queryItem.barCode : ""
                    }}
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="padding-left:15%">
                <el-form-item label="出生日期：">
                  <span style="color:red">
                    {{
                    queryItem.birthTime ? queryItem.birthTime : ""
                    }}
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="padding-left:5%">
                <el-form-item label="性别：">
                  <span style="color:red">
                    {{
                    queryItem.babySex.data ? queryItem.babySex.data : ""
                    }}
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="padding-left:15%">
                <el-form-item label="实验项目：">
                  <span style="color:red">
                    {{
                    queryItem.experimentKeywords
                    ? queryItem.experimentKeywords.key
                    : ""
                    }}
                  </span>
                </el-form-item>
              </el-col>
            </el-col>-->
            <el-col :span="24">
              <el-table
                v-loading="dsLoading"
                :data="detailsList"
                ref="detailsTable"
                style="width: 100%;padding:5px;max-height:300px;overflow: auto;"
                :header-cell-style="{
                  background: '#333333',
                  color: '#ffffff',
                  textAlign: 'center'
                }"
                @selection-change="onSelectDetailsChange"
                @row-click="clickRowItem"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column align="center" type="index" width="35" />
                <el-table-column align="center" prop="barCode" label="条形码号" width="150" />
                <el-table-column align="center" prop="momName" label="母亲姓名" />
                <el-table-column align="center" prop="babySex.data" label="性别" />
                <el-table-column align="center" prop="birthTime" label="出生日期">
                  <template slot-scope="scope">
                    <span>{{ scope.row.birthTime?scope.row.birthTime.substr(0, 10):'' }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="experimentKeywords.data"
                  label="实验项目"
                  show-overflow-tooltip
                />
                <el-table-column
                  align="center"
                  prop="hospitalName"
                  label="所属医院"
                  show-overflow-tooltip
                />
                <el-table-column align="center" prop="bloodNum" label="采血编号" width="150" />
                <el-table-column align="center" prop="bloodTime" label="采血日期">
                  <template slot-scope="scope">
                    <span>{{ scope.row.bloodTime?scope.row.bloodTime.substr(0, 10):'' }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <span
                style="font-weight: 400;color:#606266;padding: 15px 0;display: block;1px solid #e8e8e8;"
              >
                已选中
                <span style="color:#1818e6;font-weight: 700;">
                  {{
                  selectDetailsData.length
                  }}
                </span>
                条，共计
                <span>{{ detailsList.length }}</span> 条结果
              </span>
            </el-col>
            <el-col :span="24">
              <div id="bottom-form">
                <el-col :span="12">
                  <el-form-item label="寄出批号：" prop="deliveryId">
                    <el-input
                      size="mini"
                      disabled
                      v-model="deleteFormData.deliveryId"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="寄出日期：" prop="deliveryTime">
                    <el-date-picker
                      style="width:100%"
                      :format="birthTimeFormat"
                      @focus="deleteFormData.deliveryTime = ''"
                      v-model="deleteFormData.deliveryTime"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="寄出人员：" prop="deliveryMan">
                    <el-input size="mini" style="width: 100%" v-model="deleteFormData.deliveryMan" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="寄出方式：">
                    <el-select
                      size="mini"
                      style="width:100%"
                      v-model="deleteFormData.deliveryWay.key"
                    >
                      <el-option
                        v-for="(item, key, index) in dicts.DELIVERY_WAY"
                        :key="item"
                        :label="item"
                        :value="key"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="快递人员：">
                    <el-input size="mini" style="width: 100%" v-model="deleteFormData.courier" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="快递批号：">
                    <el-input size="mini" style="width: 100%" v-model="deleteFormData.courierNum" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="验收部门：" prop="receiveDepart">
                    <el-input
                      size="mini"
                      style="width: 100%"
                      v-model="deleteFormData.receiveDepart"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="备注信息：">
                    <el-input
                      size="mini"
                      type="textarea"
                      style="width: 100%"
                      v-model="deleteFormData.memo"
                    />
                  </el-form-item>
                </el-col>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          size="small"
          type="primary"
          style="padding: 6px 19px;"
          @click="onSubmit('save')"
        >保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import DeliveryExpApi from "@/api/DeliveryExp.js";
import userApi from "@/api/User.js";
import { initDicts } from "@/utils/commons";

export default {
  data() {
    return {
      dicts: {
        DELIVERY_WAY: {}
      },
      // 出生日期输入格式
      birthTimeFormat: "yyyy-MM-dd",
      // 转菊花
      loading: false,
      // 递送弹窗
      DSShow: false,
      // 递送表格转菊花
      dsLoading: false,
      // 页条数
      pageSize: 10,
      // 页数
      pageIndex: 1,
      // 表格数据
      tableData: [],
      // 选中数据
      selectList: [],
      // 详情数据
      detailsList: [],
      // 详情选中数据
      selectDetailsData: [],
      total: 0,
      basicData: {
        current: 1,
        model: {
          areaId: {
            key: ""
          },
          departId: {
            key: ""
          },
          hospitalId: {
            key: ""
          }
        },
        order: "descending",
        size: 10,
        sort: "id"
      },
      // 详情表单
      deleteFormData: {
        momName: "",
        barCode: "",
        startCode: "",
        endCode: "",
        bloodArea: "",
        courier: "",
        courierNum: "",
        courierStatus: {
          data: "",
          key: ""
        },
        createUpdate: 0,
        deliveryDepart: "",
        deliveryId:
          new Date().getFullYear().toString() +
          ((new Date().getMonth() + 1).toString() < 10
            ? "0" + (new Date().getMonth() + 1).toString()
            : (new Date().getMonth() + 1).toString()) +
          (new Date().getDate().toString() < 10
            ? "0" + new Date().getDate().toString()
            : new Date().getDate().toString()) +
          new Date().getHours().toString() +
          new Date().getMinutes().toString() +
          new Date().getSeconds().toString(),
        deliveryMan: this.$store.state.account.user.name,
        deliveryTime:
          new Date().getFullYear().toString() +
          "-" +
          ((new Date().getMonth() + 1).toString() < 10
            ? "0" + (new Date().getMonth() + 1).toString()
            : (new Date().getMonth() + 1).toString()) +
          "-" +
          (new Date().getDate().toString() < 10
            ? "0" + new Date().getDate().toString()
            : new Date().getDate().toString()),
        deliveryWay: {
          data: "",
          key: ""
        },
        isDel: 0,
        memo: "",
        receiveDepart: "",
        receiveDesc: "",
        receiveMan: ""
      },
      // 当前条形码数据
      queryItem: {
        momName: "",
        barCode: "",
        birthTime: "",
        babySex: {
          data: ""
        },
        experimentKeywords: ""
      },
      deleteRules: {
        deliveryId: [
          { required: true, message: "请填写寄出批号", trigger: "change" }
        ],
        deliveryTime: [
          { required: true, message: "请选择寄出日期", trigger: "change" }
        ],
        deliveryMan: [
          { required: true, message: "请填写寄出人员", trigger: "change" }
        ],
        receiveDepart: [
          { required: true, message: "请选择验收部门", trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    // 获取字典
    initDicts(["DELIVERY_WAY"], this.dicts);
    let queryParams = {
      size: 10,
      current: 1,
      sort: "id",
      order: "descending",
      model: {
        nation: { key: "" },
        education: { key: "" },
        positionStatus: { key: "" },
        org: { key: null },
        station: { key: null },
        sex: { code: "" },
        account: this.$store.state.account.user.account
      },
      map: {},
      timeRange: null
    };
    // 获取用户组织
    userApi.page(queryParams).then(response => {
      const res = response.data;
      if (res.isSuccess) {
        this.deleteFormData.deliveryDepart = res.data.records[0].org.key;
        this.basicData.model.departId.key = res.data.records[0].org.key;
        this.getList(this.basicData.model);
      }
    });
  },
  methods: {
    // 按钮
    onSubmit(type) {
      if (type == "save") {
        if (this.selectDetailsData.length == 0) {
          this.$message.error("请勾选条目!");
          return;
        }
        this.$refs["basicForm"].validate(valid => {
          if (valid) {
            let data = {
              bloodDeliverySaveDTOList: [],
              sampleExpressSaveDTO: this.deleteFormData
            };
            this.selectDetailsData.forEach((item, index) => {
              data.bloodDeliverySaveDTOList[index] = {
                barCode: item.barCode,
                sampleId: item.id
              };
            });

            DeliveryExpApi.sampleDelivery.deliverySave(data).then(res => {
              if (res.status === 200) {
                this.$message({
                  type: "success",
                  message: "保存成功!"
                });
                this.getList(this.basicData.model);
                this.DSShow = false;
              } else {
                this.$message.error("保存失败!");
              }
            });
          } else {
            return false;
          }
        });
      }
    },
    // 输入选中
    clickIndexSelect() {
      // 清空选中数据
      this.$refs.detailsTable.clearSelection();
      this.detailsList.filter((item, index) => {
        if (index < this.deleteFormData.endCode) {
          this.$refs.detailsTable.toggleRowSelection(item); //选中
        }
        if (item.barCode == this.deleteFormData.barCode) {
          this.$refs.detailsTable.toggleRowSelection(item); //选中
        }
      });
    },
    // 详情-根据输入条形码号过滤
    queryBarCode() {
      this.detailsList.filter((item, index) => {
        if (item.barCode == this.deleteFormData.barCode) {
          this.queryItem = item;
          this.deleteFormData.barCode = "";
          this.$refs.detailsTable.toggleRowSelection(item); //选中
        }
      });
    },
    // 选择表格数据
    onSelectChange(data) {
      this.selectList = data;
    },
    // 详情选中
    onSelectDetailsChange(data) {
      this.selectDetailsData = data;
    },
    // 点击某一行
    clickRowItem(data) {
      this.$refs.detailsTable.toggleRowSelection(data); //选中
    },
    // 点击递送
    clickDS() {
      this.deleteFormData.deliveryId =
        new Date().getFullYear().toString() +
        ((new Date().getMonth() + 1).toString() < 10
          ? "0" + (new Date().getMonth() + 1).toString()
          : (new Date().getMonth() + 1).toString()) +
        (new Date().getDate().toString() < 10
          ? "0" + new Date().getDate().toString()
          : new Date().getDate().toString()) +
        new Date().getHours().toString() +
        new Date().getMinutes().toString() +
        new Date().getSeconds().toString();

      if (this.selectList.length > 1) {
        this.$message.error("只能选择一条数据");
      } else if (this.selectList.length == 0) {
        this.$message.error("请选择数据");
      } else {
        this.DSShow = true;
        this.dsLoading = true;
        DeliveryExpApi.sampleDelivery
          .waitDeliverySample(this.selectList[0])
          .then(res => {
            if (res.status === 200) {
              this.detailsList = res.data.data.list;
              this.deleteFormData.receiveDepart = res.data.data.departName;
              this.dsLoading = false;
            } else {
              this.$message.error("数据出错请刷新后重试");
            }
          });
      }
    },
    // 获取数据
    getList(data) {
      this.loading = true;
      DeliveryExpApi.sampleDelivery
        .page(data)
        .then(res => {
          if (res.data.data) {
            this.tableData = [];
            this.tableData = [res.data.data];
          }
        })
        .finally(() => (this.loading = false));
    },
    //点击全选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击分页
    handleSizeChange: function(val) {
      this.basicData.size = val;
      this.getList(this.basicData.model);
    },
    // 选择页码
    handleCurrentChange: function(currentPage) {
      this.basicData.current = currentPage;
      this.getList(this.basicData.model);
    },
    // 出生日期输入
    changeBirthTime(v) {
      this.deleteFormData.deliveryTime = v;
      if (this.deleteFormData.deliveryTime) {
        this.birthTimeFormat = "yyyy-MM-dd";
      } else {
        this.birthTimeFormat = "MMdd";
      }
    }
  },
  watch: {
    "deleteFormData.deliveryTime": function(v) {
      this.changeBirthTime(v);
    }
  }
};
</script>

<style lang="less">
.flex {
  display: flex;
  align-items: center;
  justify-content: center;
}
#sampleDelivery {
  #bottom-form,
  #top-form {
    .el-form-item__content {
      width: 90%;
    }
  }
}
</style>
